package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.AbsSuperApplication;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UserInfoBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.LoginMessageEvent;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.AesUtil;
import com.weixin.paleituo.util.DeviceUuidFactory;
import com.weixin.paleituo.util.KeybordS;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.PreferencesUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoginNewItemView;

import org.greenrobot.eventbus.EventBus;

import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Author yichao
 * Time  2017/11/27 16:44
 * Dest  登录页
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.tv_jumpover_activity_login)
    TextView mTvJumpoverActivityLogin;
    @BindView(R.id.loginNewItemView_phone_number_acitivity_login)
    LoginNewItemView mLoginNewItemViewPhoneNumberAcitivityLogin;
    @BindView(R.id.loginNewItemView_password_acitivity_login)
    LoginNewItemView mLoginNewItemViewPasswordAcitivityLogin;
    @BindView(R.id.tv_login_activity_login)
    TextView mTvLoginActivityLogin;
    @BindView(R.id.tv_register_activity_login)
    TextView mTvRegisterActivityLogin;
    @BindView(R.id.tv_forgetpassword_activity_login)
    TextView mTvForgetpasswordActivityLogin;
    @BindView(R.id.tv_vistor_activity_login)
    TextView mTvVistorActivityLogin;


    private boolean isShowPassword = false;
    private ImageView mImagViewEye, mIvDeletcPhone;
    private EditText mEtPassword;
    private EditText mEtPhoneNumber;
    private String mPasswordContet = "";
    private String mPhoneContent = "";
    //  private UpLoadPopuWindow mUpLoadPopuWindow;
    private Disposable mDisposable;
    private Dialog mLoadingDialog;
    private boolean mBooleanExtra;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_login);
        // Retrofit

    }

    public static void startActivity(Context context, Boolean isTokenDisable) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(Contans.ISTOKEN_DISABLE, isTokenDisable);
        context.startActivity(intent);

    }

    @Override
    protected void initEvent() {
        super.initEvent();

        mEtPhoneNumber.setInputType(InputType.TYPE_CLASS_PHONE);


        //    mEtPhoneActivityLogin.addTextChangedListener(new TextChangeListener(mEtPhoneActivityLogin, mIbDeleteActivityLogin));
        //mEtPasswordActivityLogin.addTextChangedListener(new TextChangeListener(mEtPasswordActivityLogin, mIbEyeActivityLogin));
        mLoginNewItemViewPasswordAcitivityLogin.getIvIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowPassword) {
                    mImagViewEye.setImageResource(R.mipmap.eye);
                    mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mEtPassword.postInvalidate();
                    mEtPassword.setSelection(mLoginNewItemViewPasswordAcitivityLogin.getEtContent().getText().length());
                    isShowPassword = true;
                } else {
                    mImagViewEye.setImageResource(R.mipmap.eyelash);
                    //隐藏密码明文
                    mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mEtPassword.postInvalidate();
                    mEtPassword.setSelection(mLoginNewItemViewPasswordAcitivityLogin.getEtContent().getText().length());
                    isShowPassword = false;
                }
            }
        });
        mEtPhoneNumber.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPhoneContent = s.toString();

                showLoginStatue(mPhoneContent, mPasswordContet);
                if (!StringUtils.isEmpty(mPhoneContent)) {
                    mIvDeletcPhone.setVisibility(View.VISIBLE);
                } else {
                    mIvDeletcPhone.setVisibility(View.INVISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });
        mEtPassword.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPasswordContet = s.toString();
                showLoginStatue(mPhoneContent, mPasswordContet);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mIvDeletcPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtPhoneNumber.setText("");
            }
        });
        mLoginNewItemViewPasswordAcitivityLogin.getEtContent().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== 0 && KeybordS.isSoftInputShow(LoginActivity.this)) {
                    KeybordS.closeKeybord(mLoginNewItemViewPasswordAcitivityLogin.getEtContent(),LoginActivity.this);

            //关闭键盘
                return true;//返回true,消费这个事件

            }

                return false;
            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
        mBooleanExtra = getIntent().getBooleanExtra(Contans.ISTOKEN_DISABLE, false);
        mImagViewEye = mLoginNewItemViewPasswordAcitivityLogin.getIvIcon();
        mEtPassword = mLoginNewItemViewPasswordAcitivityLogin.getEtContent();

        mImagViewEye.setVisibility(View.VISIBLE);

        mImagViewEye.setImageResource(R.mipmap.eyelash);
        //隐藏密码明文
        mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        mEtPassword.postInvalidate();
        mEtPassword.setSelection(mLoginNewItemViewPasswordAcitivityLogin.getEtContent().getText().length());
        isShowPassword = false;
        mEtPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mEtPassword.setLines(1);
        mEtPhoneNumber = mLoginNewItemViewPhoneNumberAcitivityLogin.getEtContent();
        mEtPhoneNumber.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        mIvDeletcPhone = mLoginNewItemViewPhoneNumberAcitivityLogin.getIvIcon();
        mEtPhoneNumber.setLines(1);
        mEtPhoneNumber.setInputType(InputType.TYPE_CLASS_PHONE);


        mTvLoginActivityLogin.setEnabled(false);
        mTvLoginActivityLogin.setFocusable(false);


    }

    /**
     * 判断登录按钮状态
     *
     * @param phoneStr
     * @param psswordStr
     */
    private void showLoginStatue(String phoneStr, String psswordStr) {
        if (UIUtils.isPhoneNumber(phoneStr) && !StringUtils.isEmpty(phoneStr) && !StringUtils.isEmpty(psswordStr)&&UIUtils.isPasswordFormat(psswordStr)) {
            //不呢点击登录
            mTvLoginActivityLogin.setEnabled(true);
            mTvLoginActivityLogin.setFocusable(true);
        } else {
            //可以点击登录
            mTvLoginActivityLogin.setEnabled(false);
            mTvLoginActivityLogin.setFocusable(false);

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }


    @OnClick(R.id.tv_jumpover_activity_login)
    public void onMTvJumpoverActivityLoginClicked() {
        if (!mBooleanExtra){
            MainActivity.startActivity(this);
        }
        finish();
    }

    @OnClick(R.id.tv_login_activity_login)
    public void onMTvLoginActivityLoginClicked(final View view) {

        if (!NetUtils.NetwrokIsUseful(this)) {
            ToastUtils.makeText(R.string.check_internet);
            return;
        }

        if (!UIUtils.isPhoneNumber(mEtPhoneNumber.getText().toString())) {
            ToastUtils.makeText(getString(R.string.check_phone_number));
            return;
        }

        if (!UIUtils.isPasswordFormat(mEtPassword.getText().toString())) {

            ToastUtils.makeText(getString(R.string.check_password_format));

            return;
        }

        final String username = mEtPhoneNumber.getText().toString();

        final String password = mEtPassword.getText().toString();
        LogUtils.i(TAG, AesUtil.aesEncrypt(username));

        LogUtils.i(TAG,AesUtil.aesDecrypt(AesUtil.aesEncrypt(username)));
        ApiUtils.getApi().login(Contans.isEncrypt?AesUtil.aesEncrypt(username):username,Contans.isEncrypt? AesUtil.aesEncrypt(password):password, DeviceUuidFactory.getInstance(LoginActivity.this).getDeviceUuid())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                if (mLoadingDialog == null) {

                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(LoginActivity.this, "");
                }
                LoadingDialogUtils.show(mLoadingDialog);
                mTvLoginActivityLogin.setEnabled(false);
                mTvLoginActivityLogin.setFocusable(false);
            }
        }).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<StatusCode<UserInfoBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

                mDisposable = d;
            }
            @Override
            public void onNext(StatusCode<UserInfoBean> value) {
                LogUtils.i(TAG, value.toString());
                boolean flag = value.isFlag();
                if (flag) {
                    ToastUtils.makeText(value.getDetailMsg());
                    BaseApplication.isLoginSuccess = true;
                    BaseApplication.sUserInfoBean = value.getData();

                    EventBus.getDefault().post(new LoginMessageEvent(BaseApplication.sUserInfoBean));
                    PreferencesUtils.getInstance().putString(Contans.username,username);
                    PreferencesUtils.getInstance().putString(Contans.password,password);
                    // 调用 Handler 来异步设置别名
                    if (BaseApplication.sUserInfoBean!=null){
                        String deviceUuid = DeviceUuidFactory.getInstance(LoginActivity.this).getDeviceUuid();
                        String localAlias = PreferencesUtils.getInstance().getString(Contans.JPUSH_SET_ALIAS, "");
                        if (!StringUtils.isEmpty(deviceUuid ) && !localAlias.equals(deviceUuid)){
                        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, deviceUuid));
                        }
                    }
                    if (!mBooleanExtra) {

                        MainActivity.startActivity(LoginActivity.this);
                    }
                    finish();
                    LogUtils.i(TAG, "登录 前 Token :" + value.getData().token);

                    LogUtils.i(TAG, "登录 后  Token  :" + BaseApplication.sUserInfoBean.token);
                } else {
                    ToastUtils.makeText(value.getDetailMsg());
                }

                LogUtils.i(TAG,"登录处理");
            }

            @Override
            public void onError(Throwable e) {
                LogUtils.i(TAG,"登录错误");
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                LogUtils.i(TAG, e.toString());
                ToastUtils.makeText("网络错误");
                showLoginStatue(mPhoneContent, mPasswordContet);


            }

            @Override
            public void onComplete() {
LogUtils.i(TAG,"登录完成");
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                showLoginStatue(mPhoneContent, mPasswordContet);
            }
        });

    }



    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.i(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(BaseApplication.mContext,
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs+alias);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    PreferencesUtils.getInstance().putString(Contans.JPUSH_SET_ALIAS,alias);

                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
            //ExampleUtil.showToast(logs, getApplicationContext());
        }
    };

    @OnClick(R.id.tv_register_activity_login)
    public void onMTvRegisterActivityLoginClicked() {
        RegisterActivity.startActivity(this);
    }

    @OnClick(R.id.tv_forgetpassword_activity_login)
    public void onMTvForgetpasswordActivityLoginClicked() {
        //忘记密码
        ForgetPasswordActivity.startActivity(this);
    }

    @OnClick(R.id.tv_vistor_activity_login)
    public void onMTvVistorActivityLoginClicked() {
        MainActivity.startActivity(this);
        finish();
    }
    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        AbsSuperApplication.finishAllActivity();
    }
}
